﻿using System;
using System.Web.UI;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using System.ComponentModel;
using Marbles.Core.Content.Profiles;
using System.Web;

namespace Marbles.Core.Controls
{
    [ToolboxData("<{0}:UserProfileEditor runat=server></{0}:UserProfileEditor>")]
    public class UserProfileEditor : CompositeControl
    {

        [Category("Profile")]
        public string UserId
        {
            get
            {
                object obj = ViewState["UserId"];
                return (obj == null) ? "" : obj.ToString();
            }
            set { ViewState["UserId"] = value; }
        }

        [Category("Profile")]
        public string SiteId
        {
            get
            {
                object obj = ViewState["SiteId"];
                return (obj == null) ? string.Empty : obj.ToString();
            }
            set { ViewState["SiteId"] = value; }
        }

        [Category("Appearance")]
        public Table ChildTable
        {
            get
            {
                this.EnsureChildControls();
                return this.cTblForm;
            }
        }

        [Category("Events")]
        public event EventHandler ProfileUpdated;

        private Table cTblForm;
        private Button SaveButton;

        protected override void CreateChildControls()
        {
            cTblForm = new Table();
            cTblForm.ID = "Table";
            cTblForm.ApplyStyle(this.CreateControlStyle());

            if (string.IsNullOrEmpty(this.UserId)) { return; }

            if (string.IsNullOrEmpty(this.SiteId))
            {
                this.SiteId = Core.Content.Sites.SiteDefinition.GetCurrent().SiteId;
            }

            ProfileResponseCollection items = new ProfileResponseCollection(this.SiteId, this.UserId);
            int rowindex = 0;

            foreach (ProfileResponse item in items)
            {
                TableRow row = new TableRow();
                TableCell cellQuestion = new TableCell();
                TableCell blankCell = new TableCell();
                TableCell cellAnswer = new TableCell();
                blankCell.Text = "&nbsp;";
                row.ID = "row_" + rowindex.ToString();
                cellQuestion.ID = "cell_" + rowindex.ToString() + "_1";
                blankCell.ID = "cell_" + rowindex.ToString() + "_2";
                cellAnswer.ID = "cell_" + rowindex.ToString() + "_3";
                cellQuestion.VerticalAlign = VerticalAlign.Top;
                cellAnswer.VerticalAlign = VerticalAlign.Top;
                cellQuestion.Text = item.Question.Description;

                switch (item.Question.QuestionType)
                {
                    case ProfileQuestionType.Date:
                        DateTime dateValue = new DateTime(1980, 1, 1, 0, 0, 0);
                        TextBox ctxtDate = new TextBox();
                        ctxtDate.ID = "Question" + item.Question.QuestionId.ToString();
                        ctxtDate.MaxLength = 10;
                        ctxtDate.Width = new Unit(100, UnitType.Pixel);
                        ctxtDate.Text = "";
                        if (DateTime.TryParse(item.Response, out dateValue))
                        {
                            ctxtDate.Text = dateValue.ToString("dd/MM/yyyy");
                        }
                        cellAnswer.Controls.Add(ctxtDate);
                        break;
                    case ProfileQuestionType.Text:
                        TextBox txtSingleLine = new TextBox();
                        txtSingleLine.ID = "Question" + item.Question.QuestionId.ToString();
                        txtSingleLine.Width = new Unit(300, UnitType.Pixel);
                        txtSingleLine.TextMode = TextBoxMode.SingleLine;
                        txtSingleLine.Text = item.Response;
                        cellAnswer.Controls.Add(txtSingleLine);
                        break;
                    case ProfileQuestionType.TextMulti:
                        TextBox txtMultiLine = new TextBox();
                        txtMultiLine.ID = "Question" + item.Question.QuestionId.ToString();
                        txtMultiLine.Width = new Unit(300, UnitType.Pixel);
                        txtMultiLine.Height = new Unit(40, UnitType.Pixel);
                        txtMultiLine.TextMode = TextBoxMode.MultiLine;
                        txtMultiLine.Text = item.Response;
                        cellAnswer.Controls.Add(txtMultiLine);
                        break;
                    case ProfileQuestionType.ImageUpload:
                        FileUpload txtUpload = new FileUpload();
                        txtUpload.ID = "Question" + item.Question.QuestionId.ToString();
                        cellAnswer.Controls.Add(txtUpload);
                        break;
                    case ProfileQuestionType.Year:
                        DropDownList drpYear = new DropDownList();
                        drpYear.ID = "Question" + item.Question.QuestionId.ToString();
                        drpYear.Items.Add(new ListItem("", ""));
                        for (int i = 1900; i <= DateTime.Now.Year; i++)
                        {
                            drpYear.Items.Add(new ListItem(i.ToString(), i.ToString()));
                        }
                        drpYear.SelectedValue = item.Response;
                        cellAnswer.Controls.Add(drpYear);
                        break;
                    case ProfileQuestionType.YesNo:
                        DropDownList drpyesNo = new DropDownList();
                        drpyesNo.ID = "Question" + item.Question.QuestionId.ToString();
                        drpyesNo.Items.Add(new ListItem("", ""));
                        drpyesNo.Items.Add(new ListItem("No", "false"));
                        drpyesNo.Items.Add(new ListItem("Yes", "true"));
                        drpyesNo.SelectedValue = item.Response;
                        cellAnswer.Controls.Add(drpyesNo);
                        break;
                    case ProfileQuestionType.YesNoChk:
                        CheckBox ChkyesNo = new CheckBox();
                        ChkyesNo.ID = "Question" + item.Question.QuestionId.ToString();
                        bool chkValue = false;
                        if (!bool.TryParse(item.Response.ToLower(), out chkValue)) { chkValue = false; }
                        ChkyesNo.Checked = chkValue;
                        cellAnswer.Controls.Add(ChkyesNo);
                        break;
                }

                row.Cells.Add(cellQuestion);
                row.Cells.Add(blankCell);
                row.Cells.Add(cellAnswer);
                cTblForm.Rows.Add(row);
                rowindex += 1;
            }


            this.Controls.Add(cTblForm);
            SaveButton = new Button();
            SaveButton.Text = "Update";
            SaveButton.ToolTip = "Save Changes to my Profile.";
            SaveButton.Click += new EventHandler(SaveButton_Click);
            this.Controls.Add(SaveButton);
        }

        protected void SaveButton_Click(object sender, EventArgs e)
        {
            this.SaveProfile();
            if (this.ProfileUpdated != null) { ProfileUpdated(this, EventArgs.Empty); }
        }

        public void SaveProfile()
        {
            ProfileResponseCollection items = new ProfileResponseCollection(this.SiteId, this.UserId);
            int rowindex = 0;
            foreach (ProfileResponse item in items)
            {
                switch (item.Question.QuestionType)
                {
                    case ProfileQuestionType.Date:
                        TextBox ctxtDate = ChildTable.FindControl("Question" + item.Question.QuestionId.ToString()) as TextBox;
                        DateTime datevalue = Marbles.Core.Connectors.DataConnection.MinimumDateTime;
                        if (!DateTime.TryParse(ctxtDate.Text.Trim(), out datevalue)) { datevalue = Marbles.Core.Connectors.DataConnection.MinimumDateTime; }
                        item.Response = datevalue.ToString("dd/MM/yyyy");
                        break;
                    case ProfileQuestionType.Text:
                        TextBox txtSingleLine = ChildTable.FindControl("Question" + item.Question.QuestionId.ToString()) as TextBox;
                        item.Response = txtSingleLine.Text.Trim();
                        break;
                    case ProfileQuestionType.TextMulti:
                        TextBox txtMultiLine = ChildTable.FindControl("Question" + item.Question.QuestionId.ToString()) as TextBox;
                        item.Response = txtMultiLine.Text.Trim();
                        break;
                    case ProfileQuestionType.Year:
                        DropDownList drpYear = ChildTable.FindControl("Question" + item.Question.QuestionId.ToString()) as DropDownList;
                        item.Response = drpYear.SelectedValue;
                        break;
                    case ProfileQuestionType.ImageUpload:
                        FileUpload txtUpload = ChildTable.FindControl("Question" + item.Question.QuestionId.ToString()) as FileUpload;
                        if (txtUpload.HasFile)
                        {
                            string dir = HttpContext.Current.Server.MapPath("/App_Data/Profiles/" + items.UserId);
                            string extn = System.IO.Path.GetExtension(txtUpload.FileName);
                            if (!System.IO.Directory.Exists(dir)) { System.IO.Directory.CreateDirectory(dir); }

                            foreach (string file in System.IO.Directory.GetFiles(dir, items.UserId + ".*"))
                            {
                                System.IO.File.Delete(file);
                            }

                            dir = System.IO.Path.Combine(dir, items.UserId + extn);
                            txtUpload.SaveAs(dir);
                            item.Response = "/App_Data/Profiles/" + items.UserId;
                        }
                        break;
                    case ProfileQuestionType.YesNo:
                        DropDownList drpyesNo = ChildTable.FindControl("Question" + item.Question.QuestionId.ToString()) as DropDownList;
                        item.Response = drpyesNo.SelectedValue.ToLower();
                        break;
                    case ProfileQuestionType.YesNoChk:
                        CheckBox ChkyesNo = ChildTable.FindControl("Question" + item.Question.QuestionId.ToString()) as CheckBox;
                        item.Response = ChkyesNo.Checked.ToString().ToLower();
                        break;
                }

                rowindex += 1;
            }

            items.Update();
        }
    }
}